package cn.operation.api.rest;


import cn.operation.api.dto.*;
import cn.operation.backend.enums.DataTypeEnum;
import cn.operation.backend.enums.MessageCodeEnum;
import cn.operation.backend.service.ItfLatestCodePondService;
import cn.operation.backend.service.PayableBillService;
import cn.operation.backend.service.ReceivableDetailService;
import cn.operation.backend.util.BusinessException;
import cn.operation.backend.util.ResultDTOWithPagination;
import cn.operation.base.model.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @FileName:
 * @Description: 账单接口
 * @author: Felix
 * @date: 2017/8/29
 */
@Controller
@RequestMapping(value = "/api/bms/bill", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "/bmsbill", description = "账单接口")
public class BmsBillRest {
    @Autowired
    private ItfLatestCodePondService itfLatestCodePondService;
    @Autowired
    private PayableBillService payableBillService;
    @Autowired
    private ReceivableDetailService receivableDetailService;

    private static final Logger LOGGER = LoggerFactory.getLogger(BmsBillRest.class);

    /**
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPayableCodes", method = RequestMethod.GET)
    @ApiOperation(value = "查询慧运车最新被修改的应付账单号列表。", notes = "查询慧运车最新被修改的应付账单号列表。", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<List<CodeDTO>> getWaybillCodes() throws Exception {
        LOGGER.info("BmsBillRest.getPayableCodes params : {}");
        ResultDTOWithPagination<List<CodeDTO>> result = new ResultDTOWithPagination<List<CodeDTO>>(true, null, "查询成功");
        try {
            List<ItfLatestCodePond> dataList = itfLatestCodePondService.queryCodes(DataTypeEnum.PAYABLE_BILL.getValue());
            List<CodeDTO> list = new ArrayList<>();
            dataList.stream().forEach(i ->{
                CodeDTO dto = new CodeDTO();
                dto.setCode(i.getCode());
                list.add(dto);
            });
            result.setData(list);
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        } catch (Exception e) {
            LOGGER.error("BmsBillRest.getPayableCodes error: {}", e);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPayableDetail", method = RequestMethod.POST)
    @ApiOperation(value = "根据账单号，获取应付账单明细信息。", notes = "根据账单号，获取应付账单明细信息。", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<BmsPayableBillDTO> getPayableDetail(@ApiParam(value = "账单号", required = true) @RequestParam("billCode") String billCode) throws Exception {
        LOGGER.info("BmsBillRest.getPayableDetail params : {}");
        ResultDTOWithPagination<BmsPayableBillDTO> result = new ResultDTOWithPagination<BmsPayableBillDTO>(true, null, "查询成功");
        try {
            BmsPayableBillDO billDO= payableBillService.queryBillByCode(billCode);
            BmsPayableBillDTO dto = new BmsPayableBillDTO();
            BeanUtils.copyProperties(billDO, dto);
            result.setData(dto);
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        } catch (Exception e) {
            LOGGER.error("BmsBillRest.getPayableDetail error: {}", e);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 查询慧运车最新被修改的应收账单号列表
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/getReceivableCodes", method = RequestMethod.GET)
    @ApiOperation(value = "查询慧运车最新被修改的应收账单号列表。。", notes = "查询慧运车最新被修改的应收账单号列表。。", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<List<CodeDTO>> getReceivableCodes() throws Exception {
        LOGGER.info("WayBillRest.getReceivableCodes params : {}");
        ResultDTOWithPagination<List<CodeDTO>> result = new ResultDTOWithPagination<List<CodeDTO>>(true, null, "查询成功");
        try {
            List<ItfLatestCodePond> dataList = itfLatestCodePondService.queryCodes(DataTypeEnum.RECEIVABLE_BILL.getValue());
            List<CodeDTO> list = new ArrayList<>();
            dataList.stream().forEach(i ->{
                CodeDTO dto = new CodeDTO();
                dto.setCode(i.getCode());
                list.add(dto);
            });
            result.setData(list);
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        } catch (Exception e) {
            LOGGER.error("WayBillRest.getReceivableCodes error: {}", e);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 根据账单号，获取应收账单明细信息
     * @param billCode
     * @return
     */

    @RequestMapping(value = "/getReceivableDetail" ,method = RequestMethod.POST)
    @ApiOperation(value = "根据账单号，获取应收账单明细信息",notes = "提交应付账单编号",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<ReceivableDetailDTO> getReceivableDetail(@ApiParam(value = "billCode",required = true) @RequestParam(value = "billCode",required = true) String billCode){
        LOGGER.info("BmsBillRest.getReceivableDetail param {}",billCode);
        ResultDTOWithPagination<ReceivableDetailDTO> result=new ResultDTOWithPagination<ReceivableDetailDTO>(true, null, "查询成功");
        ReceivableDetailDTO receivableDetailDTO=new ReceivableDetailDTO();
        try {
            ReceivableDetailDO receivableDetailByBillCode = receivableDetailService.getReceivableDetailByBillCode(billCode);
            BeanUtils.copyProperties(receivableDetailByBillCode,receivableDetailDTO);
            result.setData(receivableDetailDTO);
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        }catch (Exception e){
            LOGGER.info("BmsBillRest.getReceivableDetail param {}",billCode);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据应收账单号更新应收账单开票状态。
     * @param billCode
     * @param invoiceDate
     * @param invoiceNo
     * @return
     */
    @RequestMapping(value = "/submitInvoiced",method = RequestMethod.POST)
    @ApiOperation(value = "根据应收账单号更新应收账单开票状态。",notes = "填写发票信息")
    @ResponseBody
    public ResultDTOWithPagination<Object> submitInvoiced(@ApiParam(value = "应付账单号", required = true) @RequestParam("billCode") String billCode ,
                                                                            @ApiParam(value = "发票日期 例：2017-8-30", required = true) @RequestParam("invoiceDate") String invoiceDate,
                                                                            @ApiParam(value = "发票号", required = false) @RequestParam(value = "invoiceNo",required = false) String invoiceNo)
                                                                            {
        LOGGER.info("BmsBillRest.submitInvoiced param {}");
        ResultDTOWithPagination<Object> result=new ResultDTOWithPagination<Object>(true, null, "修改成功");
        BmsReceivableBill bmsReceivableBill=new BmsReceivableBill();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try{
             bmsReceivableBill.setBillCode(billCode);
             bmsReceivableBill.setInvoiceDate(format.parse(invoiceDate));
             bmsReceivableBill.setInvoiceNo(invoiceNo);
            Integer i = receivableDetailService.submitInvoiced(bmsReceivableBill);
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        }catch (Exception e){
        LOGGER.error("BmsBillRest.submitInvoiced error {}",e);
        result.setMessage("修改失败，查看单号");
        result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
        }
        return result;
    }

    /**
     * 应收账单放入单据池
     * @param receivableBillCode
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/addReceivableBill", method = RequestMethod.POST)
    @ApiOperation(value = "应收账单放入单据池。", notes = "应收账单放入单据池。", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<Object> addReceivableBill(@ApiParam(value = "应收账单单号", required = true) @RequestParam("receivableBillCode") String receivableBillCode) throws Exception {
        LOGGER.info("BmsBillRest.addReceivableBill params : {}",receivableBillCode);
        ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<Object>(true, null, "添加成功");
        try {
            itfLatestCodePondService.addCode(receivableBillCode, DataTypeEnum.RECEIVABLE_BILL.getValue());
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        } catch (Exception e) {
            LOGGER.error("BmsBillRest.addReceivableBill error: {}", e);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 应付账单放入单据池
     * @param payableBillCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addPayableBill", method = RequestMethod.POST)
    @ApiOperation(value = "应付账单放入单据池。", notes = "应付账单放入单据池。", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResultDTOWithPagination<Object> addPayableBill(@ApiParam(value = "应付账单单号", required = true) @RequestParam("payableBillCode") String payableBillCode) throws Exception {
        LOGGER.info("BmsBillRest.addPayableBill params : {}",payableBillCode);
        ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<Object>(true, null, "添加成功");
        try {
            itfLatestCodePondService.addCode(payableBillCode, DataTypeEnum.PAYABLE_BILL.getValue());
            result.setMessageCode(MessageCodeEnum.SUCCESS.getValue());
        } catch (Exception e) {
            LOGGER.error("BmsBillRest.addPayableBill error: {}", e);
            result.setMessageCode(MessageCodeEnum.SERVER_ERROR.getValue());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }
}
